{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 二分查找"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "首先，假设表中元素是按升序排列\n",
    "将表中间位置记录的关键字与查找关键字比较，如果两者相等，则查找成功；\n",
    "否则利用中间位置记录将表分成前、后两个子表\n",
    "如果中间位置记录的关键字大于查找关键字，则进一步查找前一子表，否则进一步查找后一子表。\n",
    "重复以上过程，直到找到满足条件的记录，使查找成功，或直到子表不存在为止，此时查找不成功。\n",
    "\n",
    "\n",
    "<img src=\"./binary_search.png\" style=\"margin-left:0px;\"/>\n",
    "\n",
    "伪装：找出有问题的git版本号  \n",
    "伪装：最近120天的数据中，有一天的格式有问题，找出这一天"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def binary_search(alist, item):\n",
    "    \"\"\"二分查找 非递归方式，返回结果索引\"\"\"\n",
    "    n = len(alist)\n",
    "    start = 0\n",
    "    end = n - 1\n",
    "    # 通过循环，不断变更start和end，来缩小搜索范围，每次缩小一半\n",
    "    while start <= end:\n",
    "        mid = (start + end) // 2\n",
    "        if alist[mid] == item:\n",
    "            return mid\n",
    "        elif item < alist[mid]:\n",
    "            end = mid - 1\n",
    "        else:\n",
    "            start = mid + 1\n",
    "    return -1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "binary_search([1,2,3,4,5,6], 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "binary_search([1,2,3,4,5,6], 3.5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
